#coding:utf-8

from PIL import Image


# 打开图片,convert图像类型有L,RGBA
img = Image.open('1.jpg').convert('L')
img = img.transpose(Image.ROTATE_90)
#img.show();print(img.size[0],img.size[1])


# 将黑白图转化为0-1表示
def blackWrite(img):
    pixelShift = []
    for x in range(img.size[0]):
        rowList = []
        for y in range(img.size[1]):
            # 存在单一像素点不是纯黑纯白,取50为黑白分界线
            if img.getpixel((x,y)) < 50:
                rowList.append(0)
            else:
                rowList.append(1)
        pixelShift.append(rowList)
    return pixelShift


# 统计白色像素点个数
def countWrite(pixel):
    count = 0
    for x in range(len(pixel)):
        for y in range(len(pixel[0])):
            if pixel[x][y] == 1:
                count += 1
    return count


resultPixel = blackWrite(img)
result = countWrite(resultPixel)
print('白色像素点个数有:', result)
print('白色所占面积比例为:', result/(len(resultPixel)*len(resultPixel[0])))
